package com.saint.farmshop.Mapper.MapperImpl;

import com.saint.farmshop.Entity.Article;
import com.saint.farmshop.Mapper.ArticleMapper;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 文章映射器
 *
 * @author Saint
 * @date 2022/06/15
 */
@Repository
public class ArticleMapperImpl implements ArticleMapper {

    @Resource
    MongoTemplate mongoTemplate;

    private final String COLLECTION_NAME = "article";

    @Override
    public Article addArticle(Article article) {
        System.out.println(article);
        article.setStatus(1).setUpdateTime(LocalDateTime.now().plusHours(8));
        return mongoTemplate.insert(article, COLLECTION_NAME);
    }

    @Override
    public Article updateArticle(Article article) {
        article.setUpdateTime(LocalDateTime.now().plusHours(8));
        article.setStatus(1);
        return mongoTemplate.save(article, COLLECTION_NAME);
    }

    @Override
    public boolean deleteArticle(String id) {
        return mongoTemplate.remove(new Article(id), COLLECTION_NAME).getDeletedCount() > 0;
    }

    @Override
    public Article getArticleById(String id) {
        return mongoTemplate.findById(id, Article.class, COLLECTION_NAME);
    }

    @Override
    public List<Article> getArticleList() {
        return mongoTemplate.findAll(Article.class, COLLECTION_NAME);
    }

    @Override
    public List<Article> getArticleList(Integer pageNum, Integer pageSize) {
        Criteria criteria = new Criteria();
        criteria.and("status").is(1);
        Query query = new Query(criteria);
        query.skip((pageNum - 1) * pageSize);
        query.fields().exclude("status");
        query.limit(pageSize);
        return mongoTemplate.find(query, Article.class, COLLECTION_NAME);
    }

    List<Article> getArticle(Integer pageNum, Integer pageSize, Criteria criteria) {
        Query query = new Query(criteria);
        int skip = (pageNum - 1) * pageSize;
        query.skip(skip);
        query.limit(pageSize);
        query.fields().exclude("status");
        return mongoTemplate.find(query, Article.class, COLLECTION_NAME);
    }
}
